package com.fast.security.handler;

import com.fast.constants.CacheConstants;
import com.fast.pojo.AjaxResult;
import com.fast.pojo.dto.SecurityUserDTO;
import com.fast.pojo.dto.TokenDTO;
import com.fast.pojo.vo.LoginResultVO;
import com.fast.utils.jwt.JwtUtils;
import com.fast.utils.redis.RedisCache;
import com.fast.utils.response.ResponseUtil;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author ruan cai yuan
 * @version 1.0
 * @fileName com.fast.security.handler.SuccessHandler
 * @description: 登录成功的拦截器
 * @since 2024/6/23 14:47
 */
@Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
    @Resource
    private RedisCache redisCache;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        Object principal = authentication.getPrincipal();
        if (principal instanceof SecurityUserDTO) {
            SecurityUserDTO dto = (SecurityUserDTO) principal;
            //生成Token
            TokenDTO tokenDTO = new TokenDTO();
            tokenDTO.setId(dto.getSysUserDo().getUserId());
            tokenDTO.setUserName(dto.getSysUserDo().getUserName());
            tokenDTO.setAvatarPath(dto.getSysUserDo().getUserAvatar());
            String token = JwtUtils.getToken(tokenDTO);
            //用户信息存储到redis中,24小时到期
            redisCache.setCacheObject(CacheConstants.LOGIN_INFO_KEY + dto.getUsername(), dto, 24, TimeUnit.HOURS);
            //返回客户端
            LoginResultVO loginResultVO = new LoginResultVO();
            loginResultVO.setToken(token);
            loginResultVO.setUserRoutes(dto.getUserRoutes());
            loginResultVO.setBackAuthorizedUris(dto.getBackAuthorities());
            AjaxResult success = AjaxResult.success(loginResultVO);
            ResponseUtil.responseData(response, success, MediaType.APPLICATION_JSON_VALUE);
        }
    }
}
